import Link from 'next/link'; import { notFound, redirect } from 'next/navigation'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { isAdmin } from '@/app/lib/admin'; import { displayOrderId, adminStatusLabel } from '@/app/lib/orders'; import { defaultModelFor, GEMINI_IMAGE_MODEL, OPENAI_IMAGE_MODEL } from '@/app/lib/image-models'; import { activeProofRevision, customerRevisions, feedbackOnCurrentProof, orderConversation, orderMessageConfig } from '@/app/lib/order-messages'; import { getOrderCustomer } from '@/app/lib/order-customer'; import { defaultPromptFor, customStyleStarterPrompt, geminiPromptFor, geminiCustomStylePrompt, aspectSpecFromFrame, withAspect, withLettering, withArtistNote, letteringFontLabel } from '@/app/lib/image-gen'; import { frameAspect, type Orientation } from '@/app/lib/pricing'; import type { FrameId } from '@/app/data/frames'; import { STYLE_CATALOG } from '@/app/data/styleCatalog'; import { BACKGROUND_COLORS, type BgColorId } from '@/app/data/backgrounds'; import { AdminEditor } from './editor'; import { AdminCancel } from './admin-cancel'; import { PrinterOrder } from './printer-order'; export const dynamic = 'force-dynamic'; const historyFields = 'id, model, prompt, clean_url, published, created_at'; export default async function AdminOrderPage( { params }: { params: Promise<{ id: string }> }, ) { const { id } = await params; const user = await getCustomerUser(); if (!user) redirect(`/login?next=/admin/orders/${id}`); if (!isAdmin(user.email)) redirect('/orders'); const admin = commerceDb(); const [{ data: order }, history] = await Promise.all([ admin.from('orders').select('*').eq('id', id).single(), admin.from('generations').select(`${historyFields}, rejected_at`).eq('order_id', id).order('created_at', { ascending: false }), ]); if (!order) notFound(); const customerDetails = getOrderCustomer(order, true); let generations = history.data; let historyError = history.error; if (historyError?.code === '42703' && historyError.message.includes('rejected_at')) { console.warn('[portrait history] loading without rejection timestamps', { code: historyError.code }); const fallback = await admin.from('generations').select(historyFields).eq('order_id', id).order('created_at', { ascending: false }); generations = fallback.data?.map(g => ({ ...g, rejected_at: null })) ?? null; historyError = fallback.error; } if (historyError) console.error('[portrait history] could not load renders', { code: historyError.code }); const cfg = (order.config ?? {}) as { styleId?: string; commissionName?: string | null; productId?: 'matted' | 'canvas' | 'classic' | 'stretched'; size?: string; orientation?: Orientation; frame?: string; matteId?: string | null; bgColorId?: string; bgCustom?: string; fontId?: string; includeName?: boolean; artistNote?: string; }; const styleId = cfg.styleId ?? ''; const commissionName = cfg.commissionName ?? null; const artistNote = (cfg.artistNote ?? '').trim(); // Resolve the customer's chosen background colour into { hex, label } — // BUT only when the picked style actually exposes the picker // (hasSolidBackground) AND the order isn't a custom-style commission // (which inherits its background from the uploaded reference). Otherwise // the bgColorId on the order is the picker's default ('warmWhite') from // a skipped step and would be misleading to honour. const styleEntry = STYLE_CATALOG.find(s => s.id === styleId); const hasCustomStyle = !!order.custom_style_url; const showsBackground = !!styleEntry?.hasSolidBackground && !hasCustomStyle; const customerBackground = showsBackground ? (cfg.bgColorId === 'custom' ? { hex: (cfg.bgCustom ?? '').trim() || '#fbf6ea', label: 'Custom' } : cfg.bgColorId && cfg.bgColorId in BACKGROUND_COLORS ? { hex: BACKGROUND_COLORS[cfg.bgColorId as BgColorId].hex, label: BACKGROUND_COLORS[cfg.bgColorId as BgColorId].label } : null) : null; // Resolve the customer's lettering selection (name + font) for the // "named" portrait variants. Same gating as bg: only when the style // exposes a name toggle (allowsName), the customer actually turned it // on, AND it isn't a custom-style commission. Used both for the AI // generation directive and the admin-side display badge. const showsLettering = !!styleEntry?.allowsName && !hasCustomStyle && !!cfg.includeName; const letteringName = (cfg.commissionName ?? '').trim(); const letteringFontId = cfg.fontId ?? null; const customerLettering = showsLettering && letteringName && letteringFontId ? { name: letteringName, fontId: letteringFontId, fontLabel: letteringFontLabel(letteringFontId) ?? letteringFontId } : null; const revisions = customerRevisions(order.config, order.revision_note, order.updated_at); const messages = orderConversation(order.config, order.revision_note, order.updated_at); const customStyleDescription = (order.custom_style_description as string | null) ?? null; const customStyleAnalyzedAt = (order.custom_style_analyzed_at as string | null) ?? null; // Each model gets its OWN prompt — they're prompted differently: // • OpenAI uses the full prose image brief. For custom // styles that's the two-image starter prompt, with GPT-4o Vision's // cached style description baked in (its /images/edits endpoint // can't see the style image, only read a description of it). // • Gemini uses the compact "ingredient" prompt — the style essence // for catalog styles, or (for custom orders) a lean prompt that // leans on the uploaded style reference it receives directly. // The editor keeps both and swaps on model switch (remembering edits). // Shape the prompts for the customer's frame aspect so the render is // composed for the real canvas, not a square. No-op for square frames. const aspectSpec = aspectSpecFromFrame(frameAspect(cfg.productId, cfg.size, cfg.orientation ?? 'portrait')); // The customer's bg colour is woven NATIVELY into the catalog prompts // for hasSolidBackground styles via {{BG_HEX}} / {{BG_LABEL}} // placeholders that defaultPromptFor / geminiPromptFor substitute in. // Pass null for custom-style orders (the reference defines the ground) // and for non-hasSolidBackground styles (their prompts carry no // placeholders, so substitution is a no-op anyway). const letteringDirective = customerLettering ? { name: customerLettering.name, fontId: customerLettering.fontId, include: true } : null; // Wrappers compose around the bg-substituted base prompt: aspect → // lettering → artist note. Artist note sits OUTERMOST (first thing the // model reads) and is applied uniformly across all four paths. // geminiCustomStylePrompt still accepts the note for backwards compat // but we pass null here to avoid duplicating it with withArtistNote. const openaiPrompt = withArtistNote( withLettering( withAspect( hasCustomStyle ? customStyleStarterPrompt(commissionName, customStyleDescription) : defaultPromptFor(styleId, commissionName, customerBackground), aspectSpec, ), letteringDirective, ), artistNote, ); const geminiPrompt = withArtistNote( withLettering( withAspect( hasCustomStyle ? geminiCustomStylePrompt(null) : geminiPromptFor(styleId, customerBackground), aspectSpec, ), letteringDirective, ), artistNote, ); const initialPrompts = { [OPENAI_IMAGE_MODEL]: openaiPrompt, [GEMINI_IMAGE_MODEL]: geminiPrompt, } as const; const customer = await customerDetails; const orderRef = displayOrderId(order.id); const shipping = order.shipping_address as { name?: string | null; address?: { line1?: string | null; line2?: string | null; city?: string | null; state?: string | null; postal_code?: string | null; country?: string | null; } | null; } | null; const address = shipping?.address; const cityAndState = [address?.city, address?.state].filter(Boolean).join(', '); const shippingLines = [ address?.line1, address?.line2, [cityAndState, address?.postal_code].filter(Boolean).join(' '), address?.country, ].filter(line => typeof line === 'string' && line.trim()); return (
← All commissions

{customer.name || orderRef}

{customer.name && {orderRef}} {styleId && {styleEntry?.name ?? styleId}} {adminStatusLabel(order.status)}

Customer contact

{order.user_email} {customer.phone && {customer.phone}}

Shipping address

{shipping?.name || shippingLines.length > 0 ? (
{shipping?.name && {shipping.name}} {shippingLines.map((line, i) => {line})} {shippingLines.length === 0 && Address not provided}
) : Address not provided}
({ id: g.id, model: g.model, prompt: g.prompt, cleanUrl: g.clean_url, published: order.current_generation_id ? g.id === order.current_generation_id : g.published, rejectedAt: g.rejected_at as string | null, createdAt: g.created_at, }))} historyUnavailable={!!historyError} />
); }